<template>
    <div>
      <q-list bordered class="rounded-borders  no-shadow">
        <q-expansion-item
          @show="show"
          switch-toggle-side
          header-class="bg-grey-2"
          expand-separator
          label="UNSPSC"
        >
          <q-separator />
          <template v-slot:header>
            <div align="right" style="padding-top:5px;">UNSPSC</div>
            <div  style="position: absolute;right:0;top:3px;z-index:86;margin-right:30px;">
            <q-btn size="xs" outline color="nlack" :label="$t('保存')" @click.stop="saveUnsapsc"/>
            <!-- <q-btn size="xs" outline color="nlack" :label="$t('编辑')" @click.stop="modify"  style="margin-left:10px;" v-if="ischeck==2"/> -->
            </div>
          </template>
            <div class="row gutter-lg" style="height:100%;">
              <div class="col-12" style="min-height:220px;border-right:1px solid #ccc;padding:3px;">
                <q-tabs
                  v-model="caTab"
                  inline-label
                  dense
                  class="bg-grey-2 text-teal"
                  active-color="primary"
                  indicator-color="primary"
                  align="left"
                  :breakpoint="0"
                  narrow-indicator
                >
                  <q-tab name="tab1"  label="待选UNSPSC" />
                  <q-tab name="tab2"  label="已选UNSPSC" />
                </q-tabs>
                <q-separator />
                <q-tab-panels v-model="caTab" animated>
                  <q-tab-panel class="q-pa-none" name="tab1">
                    <div>
                      <el-input v-model="seachForm.name" style="width:240px;margin:10px 0px 10px 40px;height:36px;" placeholder="请输入完整的INSPSC名称">
                        <el-button slot="append" @click="clear"><i class="el-icon-close"></i></el-button>
                      </el-input>
                      <el-button type="primary" size="medium" style="margin-left:15px;" @click="findtree">搜索</el-button>
                    </div>
                    <!-- <q-tree
                      :nodes="data"
                      node-key="id"
                      ref="tree"
                      color="primary"
                      :expanded.sync="expanded"
                      :tick-strategy="tickStrategy"
                      :selected.sync="selected"
                      :ticked.sync="ticked"
                      @lazy-load="onLazyLoad"></q-tree> -->
                      <q-tree
                        v-if="data.length != 0"
                        style="margin-left:10px;"
                        :nodes="data"
                        node-key="id"
                        ref="tree"
                        color="primary"
                        default-expand-all
                        :expanded.sync="nodeExpand"
                        :tick-strategy="tickType"
                        :selected.sync="selected"
                        :ticked.sync="ticked"
                        @update:ticked="tickeds"
                        @lazy-load="onLazyLoad"></q-tree>
                  </q-tab-panel>
                  <q-tab-panel class="q-pa-none" name="tab2">
                    <q-table
                      flat
                      dense
                      class="bg-white"
                      :data="dataDep"
                      :columns="columnsDep"
                      row-key="id"
                      separator="cell"
                      selection="multiple"
                      :selected.sync="selectedDep"
                      :visible-columns="visibleColumnsDep"
                      :pagination.sync="paginationDep"
                      :rows-per-page-options="[10, 20, 30, 40]"
                      :filter="searchFormDep"
                      no-data-label="暂无数据"
                      table-class="h-custom"
                      @request="getUnspsc"
                    >
                      <template v-slot:top-right="props">
                        <q-select
                          v-model="visibleColumnsDep"
                          multiple
                          borderless
                          options-dense
                          :display-value="$t('显示列')"
                          emit-value
                          map-options
                          :options="columnsDep"
                          option-value="name"
                          class="q-mx-lg"
                        >
                          <template v-slot:option="scope">
                            <q-item
                              v-bind="scope.itemProps"
                              v-on="scope.itemEvents"
                              v-if="!scope.opt.required"
                            >
                              <q-item-section avatar>
                                <q-toggle color="blue" v-model="visibleColumnsDep" :val="scope.opt.name" />
                              </q-item-section>
                              <q-item-section style="min-width:60px">
                                {{ scope.opt.label }}
                              </q-item-section>
                            </q-item>
                          </template>
                        </q-select>
                        <q-toggle
                          v-model="searchToggleDep"
                          left-label
                          label="搜索"
                          color="blue"
                          checked-icon="check"
                          unchecked-icon="clear"
                          keep-color
                        />
                        <q-btn
                          flat round dense
                          :icon="props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'"
                          @click="props.toggleFullscreen"
                          class="q-ml-md"
                        />
                      </template>
                      <template v-if="searchToggleDep" v-slot:top-row="props">
                        <q-tr :props="props">
                          <q-td>
                            <q-btn color="primary" dense flat icon="search"/>
                          </q-td>
                          <q-td v-for="col in props.cols" :key="col.name" class="relative-position">
                            <!-- <q-btn color="primary" dense flat icon="search" class="absolute-center" v-if="col.name==='action'" @click="listGet({ pagination: pagination, filter: searchFormGroup })"/> -->
                            <q-input dense outlined v-model="searchFormDep[col.name]"/>
                          </q-td>
                        </q-tr>
                      </template>
                      <template v-slot:header="props">
                        <q-tr :props="props">
                          <q-th>
                            <q-checkbox indeterminate-value="some" dense v-model="props.selected" />
                          </q-th>
                          <q-th v-for="col in props.cols" :key="col.name" :props="props">
                            {{ col.label }}
                          </q-th>
                        </q-tr>
                      </template>
                      <template v-slot:body="props">
                        <q-tr :props="props">
                          <q-td width="52">
                            <q-checkbox dense v-model="props.selected" />
                          </q-td>
                          <q-td key="action" :props="props">
                            <q-btn-dropdown
                              color="blue"
                              size="sm"
                              dense
                              menu-anchor="bottom left"
                              menu-self="top left"
                              content-class="text-grey"
                              icon="settings">
                              <q-list dense>
                                <q-item clickable v-close-popup @click="delGroupRowDep(props.row)">
                                  <q-item-section>
                                    <q-item-label>删除</q-item-label>
                                  </q-item-section>
                                </q-item>
                              </q-list>
                            </q-btn-dropdown>
                          </q-td>
                          <q-td key="unspscCode" :props="props">{{ props.row.unspscCode  }}</q-td>
                          <q-td key="unspscName" :props="props">{{ props.row.unspscName }}</q-td>
                          <q-td key="siteCode" :props="props">{{ props.row.siteCode }}</q-td>
                          <q-td key="siteName" :props="props">{{ props.row.siteName }}</q-td>
                          <q-td key="itemName" :props="props">{{ props.row.itemName }}</q-td>
                          <q-td key="createTime" :props="props">{{ props.row.createTime }}</q-td>
                          <q-td key="createUserName" :props="props">{{ props.row.createUserName }}</q-td>
                        </q-tr>
                        <q-tr v-show="props.expand" :props="props">
                          <q-td colspan="100%">
                          </q-td>
                        </q-tr>
                      </template>
                      <template v-slot:pagination="props">
                        <q-pagination
                          v-model="paginationDep.page"
                          color="blue"
                          :max-pages="5"
                          :max="1"
                          :boundaryLinks="true"
                          :directionLinks="true"
                        />
                        共 {{ 1 }} 条
                      </template>
                    </q-table>
                  </q-tab-panel>
                </q-tab-panels>
              </div>
            </div>
          <q-card>
            <q-card-section>
            </q-card-section>
          </q-card>
        </q-expansion-item>
        <q-separator />
      </q-list>
    </div>
</template>

<script>
// import tree from '../Job/JobMain/SelectTree'
export default {
  name: 'leftNavs',
  // components: {
  //   tree
  // },
  props: {
    selectSiteId: {}
  },
  data () {
    return {
      // pagination: {
      //   page: 1,
      //   rowsPerPage: 10,
      //   rowsNumber: 10,
      //   sortBy: '',
      //   descending: Boolean
      // },
      seachForm: {
        name: ''
      },
      filter: '',
      data: [],
      ticked: [],
      expanded: [],
      selected: '',
      tickType: 'strict',
      nodeExpand: [],
      nodeSelected: '',
      addOrEdit: 1,
      tickable: true,
      tab: '',
      // ischeck: 2,
      parentId: '0',
      maximizedToggle: false,
      loadingSave: false,
      classificationdata: [],
      splitterModel: 20,
      // 品类tab
      caTab: 'tab1',
      visibleColumnsDep: [
        'unspscCode',
        'unspscName',
        // 'siteCode',
        // 'siteName',
        // 'itemName',
        'createTime',
        'createUserName'
      ],
      paginationDep: {
        page: 1,
        rowsPerPage: 10,
        rowsNumber: 10,
        sortBy: '',
        descending: Boolean
      },
      selectedDep: [],
      dataDep: [],
      datas: [],
      classification: {},
      searchToggleDep: false,
      searchFormDep: {
        unspscCode: '',
        unspscName: '',
        // siteCode: '',
        // siteName: '',
        // itemName: '',
        createTime: '',
        createUserName: ''
      },
      columnsDep: [
        { name: 'unspscCode', required: true, label: 'UNSPSC编码', align: 'left', field: 'unspscCode', sortable: true },
        { name: 'unspscName', required: true, label: 'UNSPSC名称', align: 'left', field: 'unspscName', sortable: true },
        // { name: 'siteCode', required: true, label: '地点编码', align: 'left', field: 'siteCode', sortable: true },
        // { name: 'siteName', required: true, label: '地点名称', align: 'left', field: 'siteName', sortable: true },
        // { name: 'itemName', required: true, label: '品项名称', align: 'left', field: 'itemName', sortable: true },
        { name: 'createTime', field: 'createTime', align: 'left', label: '创建时间', sortable: true },
        { name: 'createUserName', label: '创建人', align: 'left', field: 'createUserName', sortable: true }
      ]
    }
  },
  validations: {
  },
  created () {
    // this.show()
  },
  watch: {
    'selectSiteId' () {
      this.show()
    },
    'ticked' () {
      this.$forceUpdate()
      // if (this.ticked.length > 1) {
      //   this.ticked = [this.ticked[1]]
      // }
    },
    'ischeck' () {
      this.$forceUpdate()
    }
  },
  methods: {
    clear () {
      this.seachForm.name = ''
      this.getTree()
    },
    show () {
      this.$forceUpdate()
      this.getUnspsc()
    },
    nodeTicked () {
      console.log(this.$refs.tree.getTickedNodes())
    },
    modify () {
      // this.tickable = true
      // this.ischeck = 1
      this.getTree()
    },
    // 单选
    tickeds (ticked) {
      if (ticked.length > 1) {
        this.ticked = [ticked[1]]
      }
    },
    async getUnspsc () {
      await this.$api({
        method: 'get',
        url: `/mdm/item/unspsc/findByItemSiteId/${this.selectSiteId}`,
        emulateJSON: true,
        // useNotify: true,
        successCallback: ({ data }) => {
          if (data === null) {
            console.log('111111111111111')
            this.ticked = []
            // this.tickable = true
            // this.ischeck = 1
          } else {
            console.log('222222222222222222')
            console.log(data)
            this.dataDep = data
            data.forEach(item => {
              this.ticked.push(item.unspscId)
              // this.tickable = false
              // this.ischeck = 2
            })
            console.log(this.dataDep)
            this.getTree()
            // console.log(this.$refs.tree.getExpandedNodes())
          }
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    },
    // 保存
    async saveUnsapsc () {
      if (this.ticked.length !== 0) {
        await this.$api({
          method: 'put',
          url: '/mdm/item/unspsc/save',
          params: {
            itemSiteId: this.selectSiteId,
            unspscIds: this.ticked
          },
          emulateJSON: true,
          useNotify: true,
          successCallback: ({ data }) => {
            console.log(data)
            // this.tickable = false
            // this.ischeck = 2
            this.getTree()
            this.getUnspsc()
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
      } else {
        this.$q.notify({
          message: '请先选择所属UNSPSC',
          color: 'negative',
          icon: 'error_outline',
          position: 'top-right',
          timeout: 3000
        })
      }
    },
    async onLazyLoad ({ node, key, done, fail }) {
      console.log(node, key, fail)
      this.parentId = node.id
      await this.$api({
        method: 'post',
        url: '/mdm/unspsc/selectUnspscByTurn',
        params: {
          parentId: this.parentId
        },
        emulateQS: true,
        successCallback: ({ data }) => {
          let arr = []
          let simple = {}
          for (let i = 0; i < data.length; i++) {
            simple.id = data[i].id
            simple.parentId = data[i].parentId
            simple.label = data[i].name
            simple.tickable = this.tickable
            if (data[i].grade < 3 || data[i].garde === 3) {
              simple.lazy = true
            } else {
              simple.lazy = false
            }
            arr.push(simple)
            simple = {}
          }
          done(arr)
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    },
    async findtree () {
      this.data = []
      this.expanded = []
      this.number = 2
      if (this.seachForm.name === '') {
        this.getTree()
      } else {
        await this.$api({
          method: 'post',
          url: '/mdm/unspsc/getUnspscTreeBySearch',
          params: {
            name: this.seachForm.name
          },
          emulateJSON: true,
          useNotify: true,
          useLoadLayer: true,
          successCallback: ({ data }) => {
            let expandeds = []
            let selecteds = ''
            // let name = this.seachForm.name
            function findId (arr) {
              for (let i in arr) {
                if (arr[i].children instanceof Array) {
                  if (expandeds.length === 0) {
                    expandeds.push(arr[i].id)
                  } else {
                    if (expandeds.indexOf(arr[i].id) === -1) {
                      expandeds.push(arr[i].id)
                    }
                  }
                  findId(arr[i].children)
                }
              }
            }
            findId(data)
            this.data = []
            this.data = data
            console.log(this.data)
            this.selected = selecteds
            console.log(expandeds)
            this.nodeExpand = expandeds
            console.log(this.nodeExpand)
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
      }
    },
    async getTree () {
      this.$forceUpdate()
      if (this.selectSiteId.length === 0) {
        this.data = []
        this.$q.notify({
          message: '请先选择维护地点',
          color: 'negative',
          icon: 'error_outline',
          position: 'top-right',
          timeout: 3000
        })
      } else {
        this.data = []
        await this.$api({
          method: 'post',
          url: '/mdm/unspsc/selectUnspscByTurn',
          params: {
            id: this.id,
            parentId: this.parentId
          },
          emulateJSON: true,
          useLoadLayer: true,
          successCallback: ({ data }) => {
            let arr = []
            let simple = {}
            console.log(this.tickable)
            for (let i = 0; i < data.length; i++) {
              simple.id = data[i].id
              simple.parentId = data[i].parentId
              simple.label = data[i].name
              simple.tickable = this.tickable
              if (data[i].grade < 3 || data[i].garde === 3) {
                simple.lazy = true
              } else {
                simple.lazy = false
              }
              arr.push(simple)
              simple = {}
            }
            // console.log(this.$refs.tree.getExpandedNodes())
            this.data = arr
            console.log(arr)
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
  /deep/.q-item
    min-height 30px
    max-height 35px
  /deep/.el-input__inner
    height 36px
    line-height 36px
  .h-td-maxwidth
    max-width 150px
  // 去除table header checkbox 所在td的top border
  .q-table--cell-separator td, .q-table--cell-separator th
    border-width 1px
    border-top-width 0
  .expand-row-label
    display inline-block
    width 40px
    text-align left
</style>
